<script setup>
import {onMounted, ref} from "vue";
import moment from 'moment'
import cardWarp from './cardWarp.vue'
import {
  Download,
  Delete,
  Check,
  Close,
  Upload,
  Grid,
  Folder, Edit
} from '@element-plus/icons-vue'
import local from '@/axios/local'
import utils from '@/utils/storage'
import Task from './task.vue'
import createOrUpload from './createOrUpload.vue'
import {ElMessage, ElMessageBox} from "element-plus";
import MoveToFolder from "@/views/cloud/moveToFolder.vue";
import FilePreview from "./filePreview.vue";
import {useRoute} from "vue-router";
import * as uuid from "uuid";
import {invoke} from "@/utils/ipc_fn";

const taskList = ref([])
const dataList = ref([])
const selection = ref([])
const cardRef = ref()
const taskRef = ref()
const showType = ref('grid')
const createOrUploadRef = ref()
const selectType = ref('all')
const moveRef = ref(null)
const filePreviewRef = ref(null)
const file_path = ref('/www/server/nginx/conf')
const nav = ref([])
const socket = ref(window.$io)
const itemData = ref()
const old_file_path = ref('/')

function createTasks(form) {
  if (form.type === 'file') {
    let list = form.fileList
    taskList.value = list.map(el => {
      return {
        ...el,
        ...{
          status: 0,
          type: 'upload',
          create_time: new Date(),
          progress: 0,
          speed: 0,
          sftp_uuid: itemData.value.uuid,
          remote_path: file_path.value,
          uuid: uuid.v4().replaceAll('-', '')
        }
      }
    })
    taskRef.value.showTask()
  }
}

function getSelection() {
  return showType.value === 'grid' ? selection.value : cardRef.value.checkIdList

}

async function updateName(row) {
  if (row.is_folder !== 1) {
    if (row.new_name.split('.').length === 1) return ElMessage.warning('名称格式错误')
  }
  if (!row.new_name || row.new_name.trim() === '') return ElMessage.warning('请输入名称')
  if(row.new_name===row.filename) return   row.is_rename = false
  console.log(row.new_name)
  await local.post('/ssh/updateFileName', {
    sftp_uuid:itemData.value.uuid ,
    oldFilePath: file_path.value + '/' +row.filename,
    newFilePath: file_path.value + '/' +row.new_name,
  })
  await getFiles()
  row.is_rename = false
}

async function resetSearch() {
  file_path.value = '/'
  dataList.value = []
  await getFiles()
}

function move(item) {
  let arr = item ? [item] : getSelection()
  if (!arr.length) return
  moveRef.value?.show(arr)
}

async function batchDownload(item) {
  let arr = item ? [item] : getSelection()
  // 批量下载
  if (!arr.length) return
  invoke('selectFolder', '').then(async r => {
    if (!r) return
    for (let k in arr) {
      taskList.value.push({
        ...arr[k],
        ...{
          create_time: new Date(),
          progress: 0,
          name: arr[k].filename,
          type: 'download',
          sftp_uuid: itemData.value.uuid,
          status: 0,
          speed: 0,
          uuid: uuid.v4().replaceAll('-', ''),
          path: r,
          remote_path: file_path.value + '/' + arr[k].filename,
        }
      })
    }
    taskRef.value.showTask()

    ElMessage.success('操作成功')
    await getFiles()
  })


}

function rename() {
  if (!selection.value.length) return
  selection.value.forEach(item => {
    item.new_name = item.filename
    item.is_rename = true
  })
}

function toDelete(v, item) {
  let arr = item ? [item] : getSelection()
  console.log(arr, item, showType.value)
  if (!arr.length) return
  ElMessageBox.confirm(
      `确认${v === 1 ? '删除' : '恢复'}选中的文件或文件夹？`,
      '提醒',
      {
        confirmButtonText: '删除',
        cancelButtonText: '取消',
        type: 'warning',
      }
  )
      .then(async () => {
        await local.post('/ssh/unlinkFiles', {
          uuid: itemData.value.uuid,
          pathList: arr.map(el => {
            return {
              is_folder: el.is_folder,
              path: file_path.value + '/' + el.filename
            }
          })
        })
        ElMessage.success(v === 1 ? '删除成功' : '恢复成功')
        await getFiles()
      })
      .catch(() => {

      })
}

function completelyDelete(item) {
  let arr = item ? [item] : getSelection()
  if (!arr.length) return
  ElMessageBox.confirm(
      '确认彻底删除选中的文件或文件夹？',
      '提醒',
      {
        confirmButtonText: '删除',
        cancelButtonText: '取消',
        type: 'warning',
      }
  )
      .then(async () => {
        await local.post('/cloud/completelyDelete', {
          fileList: arr.map(el => {
            return {
              path: el.path,
              id: el.id
            }
          })
        })
        ElMessage.success('删除成功')
        await getFiles()
      })
      .catch(() => {

      })
}


async function goFolder(row) {
  if (row.is_folder === 1) {
    file_path.value = file_path.value === '/' ? file_path.value + row.filename : file_path.value + '/' + row.filename
    await getFiles()
  } else {
    socket.value.emit('ssh.previewFile', {
      sftp_uuid: itemData.value.uuid,
      filePath: file_path.value + '/' + row.filename
    }, r => {
      console.log(r, 'r')
      if (r.code === 200) {
        row.text = r.data.text
        row.type = r.data.type.split(':')[r.data.type.split(':').length - 1]
        filePreviewRef.value.show(row, {
          sftp_uuid: itemData.value.uuid,
          filePath: file_path.value + '/' + row.filename
        })
      } else {
        ElMessage.warning('不支持查看')
      }

    })

  }
}

async function getFiles() {
  let p = {
    ...itemData.value,
    ...{
      path: '/' + file_path.value
    }
  }
  try {
    let {data} = await local.post('/ssh/sftpGetTree', p)
    data.forEach(el => {
      el.size = el.is_folder === 1 ? '/' : utils.renderSize(el.attrs.size)
      el.atime = moment(new Date(el.attrs.atime)).format('YYYY-MM-DD HH:mm:ss')
      el.mtime = moment(new Date(el.attrs.mtime)).format('YYYY-MM-DD HH:mm:ss')
    })
    data.sort((a, b) => b.is_folder - a.is_folder);
    dataList.value = data
    old_file_path.value = file_path.value
  } catch (e) {
    file_path.value = old_file_path.value
  }


}

function onselectionchange(v) {
  selection.value = v
}

function taskAppend(item) {
  taskRef.value.appendTask(item)
}

async function getItem() {
  const route = useRoute()
  let {data} = await local.get(`/ssh/getItemById?id=${route.query.id}`)
  itemData.value = data
  await getFiles()
}


getItem()
</script>

<template>
  <div class="cloud">
    <div class="btn-group">
      <div class="input">
        <input @keyup.enter="getFiles" placeholder="请输入地址" v-model="file_path" type="text">
      </div>
      <div>
        <el-button-group v-if="selectType!=='delete'" style="margin-right: 10px" size="small" class="ml-4">
          <el-button round @click="createOrUploadRef.show('file')" type="success" :icon="Upload">上传
          </el-button>
          <el-button v-if="showType==='grid'" round @click="rename" type="primary" :icon="Edit">重命名</el-button>
          <el-button round @click="toDelete(1)" type="danger" :icon="Delete">删除</el-button>
          <el-button round @click="batchDownload()" type="primary" :icon="Download">下载</el-button>
        </el-button-group>
      </div>
      <el-radio-group style="margin-right: 10px" size="small" v-model="showType">
        <el-radio-button value="grid">
          <el-icon title="列表模式">
            <Grid/>
          </el-icon>
        </el-radio-button>
        <el-radio-button value="folder">
          <el-icon title="文件模式">
            <Folder/>
          </el-icon>
        </el-radio-button>
      </el-radio-group>
    </div>
    <div class="data-div">
      <el-table border v-if="showType==='grid'" @selection-change="onselectionchange" height="100%"
                highlight-current-row
                :data="dataList">
        <el-table-column align="center" width="40px" label="" type="selection"/>
        <el-table-column width="300" align="left" label="文件名" prop="name">
          <template #default="{row}">
            <div v-if="!row.is_rename" :title="row.longname" @click="goFolder(row)" class="folder">
              <img :src="utils.imgSrcSftp(row)" alt="">
              <span>{{ row.filename }}</span>
            </div>
            <div v-else class="rename">
              <el-input style="width: 60%;" size="default" show-word-limit maxlength="255" v-model="row.new_name"
                        clearable></el-input>
              <el-button @click="updateName(row)" size="small" type="success" style="margin-left: 15px" circle
                         :icon="Check"></el-button>
              <el-button @click="row.is_rename=false" size="small" circle :icon="Close"></el-button>
            </div>
          </template>
        </el-table-column>

        <el-table-column align="center" label="大小" prop="size"/>
        <el-table-column align="center" label="模式" prop="attrs.mode"/>
        <el-table-column show-overflow-tooltip align="center" label="最后访问时间" prop="atime"/>
        <el-table-column show-overflow-tooltip align="center" label="最后修改时间" prop="mtime"/>
      </el-table>
      <card-warp ref="cardRef" @download="batchDownload" @remove="move"
                 @preview="goFolder" @delete="(item)=>toDelete(1,item)" @restore="(item)=>toDelete(0,item)"
                 @complete-delete="completelyDelete" v-else :data="dataList"/>
    </div>
    <create-or-upload @task_success="taskAppend" :file_path="file_path" @success="createTasks" :file_type="nav"
                      ref="createOrUploadRef"/>
    <move-to-folder :file_path="file_path" @success="resetSearch" ref="moveRef"/>
    <file-preview ref="filePreviewRef"/>
    <Task @getData="getFiles" :tasks="taskList" ref="taskRef"/>
  </div>
</template>

<style scoped lang="scss">
.folder {
  display: flex;
  align-items: center;

  &:hover {
    color: var(--el-color-primary);
  }

  img {
    width: 30px;
    height: auto;
  }

  span {
    margin-left: 15px;
    cursor: pointer;
  }
}

.cloud {
  width: 100%;
  height: 100%;
  display: flex;
  flex-direction: column;

  .btn-group {
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding: 10px;

    .input {
      flex: 1;
      flex-shrink: 0;
      overflow: hidden;
      display: flex;
      justify-content: flex-start;


      input {
        flex: 1;
        padding: 0 10px;
        margin-right: 100px;
        border-radius: 3px;
        box-sizing: border-box;
        flex-shrink: 0;
        height: 30px;
        overflow: hidden;
        outline: none;
        color: black;
        border: 1px solid #ececec;
        font-size: 14px;
      }

    }
  }

  .data-div {
    flex: 1;
    flex-shrink: 0;
    padding: 10px;
    overflow: hidden;
  }

  .top-nav {
    display: flex;
    background-color: #ececec;


    ul {
      display: flex;
      justify-content: center;
      width: 100%;
      padding: 10px 0;

      .active {
        background-color: #409eff;
        color: white;
      }

      li {
        cursor: pointer;
        padding: 10px 20px;
        font-size: 15px;
        display: flex;
        align-items: center;
        transition: all 0.5s;

        i {
          margin-right: 5px;
          font-size: 16px;
        }
      }
    }
  }
}
</style>
